<template>
    <!--
  TODO 一些问题
  1 开课时 四个字段无法保存
  2 没有完整数据 teachingclassvo的select接口
    -->
    <div class="edu-page-warp graduate-arrangement">
        <inner-breadcrumb
            v-model="pathKey"
            :path="{
        label: '讲座信息',
        key:'main',
        children:[{
          label: '详情',
          key:'detail'
        }]

      }"
        ></inner-breadcrumb>
        <!-- <button v-if="pathKey != 'arrange'" @click="pathKey = 'arrange'">test</button> -->
        <lecture-information-detail
            v-if="pathKey=='detail'"
            :studentId="studentId"
            :stuName="stuName"
            @back="pathKey='main'"
        />
        <div v-show="pathKey=='main'">
            <template>
                <condition-card @reset="reset" @search="searchList">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('label.trainingLevel')"
                                :title="$t('label.trainingLevel')"
                            >
                                <dict-select v-model="queryParams.cultivationLevel" :data="options.trainingLevel"></dict-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('label.trainingCategory')"
                                :title="$t('label.trainingCategory')"
                            >
                                <dict-select v-model="queryParams.trainingCategory" :data="options.trainingCategory" filterable></dict-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('label.degreeType')"
                                :title="$t('label.degreeType')"
                            >
                                <dict-select v-model="queryParams.degreeType" :data="options.degreeType" filterable></dict-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('label.formLearning')"
                                :title="$t('label.formLearning')"
                            >
                                <dict-select
                                    v-model="queryParams.learningForm"
                                    :data="options.formLearning"
                                ></dict-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('label.grade')"
                                :title="$t('label.grade')"
                            >
                            <el-select
                                v-model="queryParams.guade"
                                :disabled="disabled"
                                :size="size"
                                :multiple="multiple"
                                clearable
                                :placeholder="$t('common.text.all')"
                                style="width: 100%;"
                                @change="handleChange"
                            >
                                <el-option :label="$t('common.text.all')" value="" v-if="showAll"/>
                                <el-option v-for="item in gradeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                            </el-form-item>
                        </el-col>
                       <el-col :span="8">
                            <el-form-item
                                :label="$t('label.enrolSeason')"
                                :title="$t('label.enrolSeason')"
                            >
                                 <dict-select
                                    v-model="queryParams.admissionSeason"
                                    :data="options.enrolSeason"
                                ></dict-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('label.college')"
                                :title="$t('label.college')"
                            >
                                <dict-select
                                    v-model="queryParams.faculty"
                                    :data="options.collegeList"
                                    filterable
                                    clearable
                                ></dict-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                filterable
                                :label="$t('label.major')"
                                :prop="major"
                                :title="$t('label.major')"
                            >
                                 <el-select v-model="queryParams.major" style="width: 100%" clearable filterable>
                                    <el-option
                                        v-for="item in options.majorList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('label.achievement')"
                                :title="$t('label.achievement')"
                            >
                                <DictSelect v-model="queryParams.achievement"  :data="options.achievement"></DictSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </condition-card>
                <el-card shadow="never">
                    <h2>{{$t('culture.lecture.listSearch')}}</h2>
                    <div class="edu-opertion-bar">
                        <el-input
                            style="width:300px"
                            placeholder="输入学号或姓名搜索"
                            prefix-icon="el-icon-search"
                            v-model="queryParams.keyword"
                            @keyup.enter.native="searchList"
                        ></el-input>
                        <edu-check-config-dialog
                            title="提示"
                            ref="checkConfigRef"
                            @close="checkConfigButton=false"
                            :data="checkConfigResult"
                        ></edu-check-config-dialog>
                        <div class="float-right">
                            <el-button
                                :disabled="exportReportButton"
                                plain
                                @click="exportReportBatch"
                            >{{$t('culture.lecture.downloadBatch')}}</el-button>
                            <el-button
                                :disabled="exportButton"
                                plain
                                @click="exportLecture"
                            >{{$t('message.export')}}</el-button>
                        </div>
                       
                    </div>
                    <edu-table
                        :data="tableData.list"
                        :total="tableData.total_"
                        :pageSize="queryParams.pageSize_"
                        :order="false"
                        @page-change="onCurrentPageChange"
                        size="mini"
                        @selection-change="handleSelectionChange"
                        class="manArrange-table"
                        stripe>
                        <el-table-column :label="$t('label.stuName')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.name}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.stuCode')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.studentId}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.grade')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.guade}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.enrolSeason')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.admissionSeasonI18n}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.trainingLevel')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.cultivationLevelI18n}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.trainingCategory')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.trainingCategoryI18n}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.degreeCategory')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.degreeTypeI18n}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.formLearning')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.learningFormI18n}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.college')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.facultyI18n}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.major')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.majorI18n}}</template>
                        </el-table-column>
                         <el-table-column :label="$t('label.numberOfLectures')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.numberOfLectures}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.numberOfReports')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.numberOfReports}}</template>
                        </el-table-column>
                        <el-table-column :label="$t('label.achievement')"   align="left" show-overflow-tooltip>
                             <template slot-scope="scope">{{scope.row.achievement}}</template>
                        </el-table-column>
                        <el-table-column
                            :label="$t('message.operating')"
                            fixed="right"
                            align="center"
                        >
                         <template slot-scope="scope">
                         <el-button
                                        type="text"
                                        @click="getLecture(scope.row)"
                                        v-if="haveLectureReport(scope.row)"
                                        size="mini"
                                    >{{$t('message.Look')}}</el-button>
                         </template>
                        </el-table-column>
                    </edu-table>
                </el-card>
            </template>
        </div>
        <edu-export-dialog ref="downloadRef" :data="exportResult"></edu-export-dialog>
    </div>
</template>
<script>
import LectureInformationApi from "common/src/api/culture/lectureInformation";
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import lectureInformationDetail from "common/src/views/culture/lectureInformation/lectureInformationdetail";
import {
    findMasterClassroom,
    updateClassroom,
    findClassRoomCourse,
    addClassroom,
    deleteClassroom,
    exportMasterClass
} from "common/src/api/coursearrangement/masterOpenClassroom";
import { getValue } from "common/src/api/commonParam";
import CourseSummaryApi from "common/src/api/course/courseSummary";
import { getGraduateDegreePage } from "common/src/api/resource/course";
import { downloadfile } from 'common/src/api/upload';
/**
 * 手工排课
 */
export default {
    name: "lectureInformation",
    components: {
        lectureInformationDetail
    },
    computed: {
        natureMap() {
            let map = {};
            let list = this.options.natureList;
            for (let i = 0; i < list.length; i++) {
                const nature = list[i];
                map[nature.value] = nature.label;
            }
            return map;
        }
    },
    data() {
       return {
            pathKey: "main",
            activeClassId: 0,
            studentId:"",
            stuName:"",
            showArrangePanel: false,
            showCondition: true,
            calendar: {},
            gradeList: [],
            options: {
                manArrangeFlag: {
                    0: this.$t("arrangement.status.unarranged"),
                    1: this.$t("arrangement.status.arranged"),
                    2: this.$t("arrangement.status.arrangedWithoutRoom"),
                    3: this.$t("arrangement.status.waitForNotify"),
                    4: this.$t("arrangement.status.waitChanged")
                },
                trainingLevel: [],
                collegeList: [],
                majorList: [],
                langList: [],
                campusList: [],
                natureList: [],
                roomType: [],
                formLearning: [], // 学习形式
                trainingCategory: [], // 培养类别
                graduateMajors: [], // 研究生专业
                degreeType: [], // 学位类型
                enrolSeason: [], //授课类型
                achievement:[
                    { label: '已获取', value: "已获取" },
                    { label: '未获取', value: "未获取" }
                ]
            },
            trainingLevel: "", // 本页面操作面向的学期，只保留硕博
            queryParams: {
                cultivationLevel: "", //培养层次 多选
                trainingCategory:"",
                degreeType:"",
                learningForm: "",
                guade: "",
                admissionSeason:"",
                faculty: "",
                major:"",
                achievement: "",
                keyword: "",
                    // trainingLevelList: [4, 6],
                pageNum_: 1,
                pageSize_: 20
            },
            courseQuery: {
                condition: {
                    courseName: ""
                },
                pageNum_: 1,
                pageSize_: 5
            },
            courses: {
                query: {
                    condition: {
                        courseName: null,
                        trainingLevel: null
                    },
                    pageNum_: 1,
                    pageSize_: 5
                },
                list: []
            },
            isEdit: false,
            tableData: {},
            selectionDatas: [],
            checkConfigButton: false,
            checkConfigResult: null,
            exportResult: null,
            exportReportResult: null
        };
    },
    created() {},
    mounted() {
        this.getOptions();
    },
    activated() {},
    watch: {
        trainingLevel(val) {
            this.queryParams.trainingLevel = val;
            this.courses.query.condition.trainingLevel = val;
        },
        pathKey(val) {
            if (val == "main") {
                this.activeClassId = 0;
                this.searchList();
            }
        },
        "queryParams.faculty": function(_new, _old) {
            if(_new){
                //* 获取模板
                this.addMajors();
            }
        }
    },
    methods: {
        onPageSizeChange(size) {
            this.queryParams.pageSize_ = size;
            this.searchList();
        },
        onCurrentPageChange(currentPage) {
            this.queryParams.pageNum_ = currentPage.pageNum;
            this.queryParams.pageSize_ = currentPage.pageSize;
            this.searchList();
        },
        getOptions() {
            let fullYear = new Date().getFullYear()+5;
             for(; fullYear > 1994; fullYear--) {
                 this.gradeList.push({value: fullYear,label: fullYear});
             }
            //筛选条件字典查询
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: [
                    "X_PYCC",
                    "X_YX",
                    "X_SKYY",
                    "X_XQ",
                    "G_ZY",
                    "X_KCXZ", // 课程性质
                    "X_JSLX", // 教室类型
                    "X_XXXS", // 学习形式
                    "X_PYLB", // 培养类别
                    "G_YJSZY", // 研究生专业
                    "X_XWLB", // 学位类型
                    "X_SKLX",//授课类型
                    "X_RXJJ",//入学季节
                ]

            };
            let promise1 = getValue("arrange_default_term1");
            let promise2 = queryDic(data);
            Promise.all([promise1, promise2]).then(responses => {


                let res = responses[1];
                if (res.code === 200) {
                    UTILS.fillSelect(
                        {
                            trainingLevel: "X_PYCC", //培养层次
                            collegeList: "X_YX",
                            majorList: "G_ZY",
                            langList: "X_SKYY",
                            campusList: "X_XQ",
                            natureList: "X_KCXZ",
                            roomType: "X_JSLX", // 教室类型
                            formLearning: "X_XXXS", // 学习形式
                            trainingCategory: "X_PYLB", // 培养类别
                            graduateMajors: "G_YJSZY", // 研究生专业
                            degreeType: "X_XWLB", // 研究生专业
                            teachingType: "X_SKLX",
                            enrolSeason:"X_RXJJ"
                        },
                        res.data,
                        this.options
                    );
                    // this.options.trainingLevel = this.options.trainingLevel.filter(
                    //     dic => dic.value === "4" || dic.value === "6"
                    // );
                    this.searchList();
                    this.isEnable = true;
                }
            });

        },
        handleSelectionChange(val) {
            this.selectionDatas = val;
        },
        pageChange(page) {
            this.queryParams.pageNum_ = page.pageNum;
            this.queryParams.pageSize_ = page.pageSize;
            this.searchList();
        },
        haveLectureReport(data) {
            return (
                data.numberOfLectures != 0
            );
        },
        searchList() {
            LectureInformationApi.lecturePage(this.queryParams, true).then(response => {
                if (response.code === 200) {
                    this.tableData = response.data;
                } else {
                    throw response.msg;
                }
            });
        },
        addMajors() {
            this.queryMajors(this.queryParams.faculty, this.queryParams.degreeType);
        },
        getGraduateDegreePage(college, degreeType) {
            const data = {
                college: college,
                page: false,
                isRecruit: 1,
                type: degreeType
            };
            return getGraduateDegreePage(data);
        },
        queryMajors(college, degreeType) { // 查询专业（研究生）
            this.options["majorList"] = [];
            Vue.set(this.queryParams, "major", "");
            let promise = this.getGraduateDegreePage(college, degreeType);
            promise.then(response => {
                let {
                    code,
                    data: { list }
                } = response;
                if (code === 200) {
                    list.sort(this.up('code'));
                    this.options.majorList = list.map(item => ({
                        value: item.code,
                        label:
                            "cn" === this.$store.getters.language
                                ? item.name
                                : item.nameEn
                    }));
                }
            });
        },
        reset() {
            for (const key in this.queryParams) {
                if (key != "calendar" && key != "trainingLevelList") {
                    // 清除学期是无意义的，排课只能针对一学期进行
                    this.queryParams[key] = "";
                }
                this.queryParams.pageNum_=1;
                this.queryParams.pageSize_=20;
            }
            this.trainingLevel = "";
            this.searchList();
        },
        up (name) {
            return function (obj1, obj2) {
            let val1 = obj1[name]
            let val2 = obj2[name]
            return val1 - val2
            }
        },
        urlEncode (str) {
            let temp = str;
            temp = (temp + '').toString();
             return encodeURIComponent(temp).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
        },
        getLecture(data) {
            this.studentId = data.studentId;
            this.stuName=data.name;
            this.pathKey = "detail";
        },
        exportLecture() {
            this.exportResult = null;
            this.$refs.downloadRef.open();
            this.exportButton = true;
            LectureInformationApi.lectureExport(this.queryParams).then(res => {
                if (res.code == 200) {
                    this.delayRequestForExport(res.data.key);
                } else {
                    this.$refs.downloadRef.close();
                    this.exportButton = false;
                }
            });
        },
        exportReportBatch() {
            this.exportReportResult = null;
            this.$refs.downloadRef.open();
            this.exportReportButton = true;
            LectureInformationApi.exportLectureReport(this.queryParams).then(res => {
                if (res.code == 200) {
                    this.delayRequestForReport(res.data.key);
                } else {
                    this.$refs.downloadRef.close();
                    this.exportReportButton = false;
                }
            });
        },
        //异步获取批量结果
        delayRequestForExport(key) {
            setTimeout(() => {
                CourseSummaryApi.getResultByKeyWithOutPre(key).then(res => {
                    this.exportResult = res.data;
                    if (res.data.status) {
                        this.$refs.downloadRef.close();
                        this.exportButton = false;

                        LectureInformationApi.downloadLecture(res.data.path)
                    } else {
                        this.delayRequestForExport(key);
                    }
                });
            }, 3000);
        },
        delayRequestForReport(key) {
            setTimeout(() => {
                CourseSummaryApi.getResultByKeyWithOutPre(key).then(res => {
                    this.exportResult = res.data;
                    if (res.data.status) {
                        this.$refs.downloadRef.close();
                        this.exportReportButton = false;
                        if(res.data.path==null){
                            this.$alert("文件报告下载失败,请重新下载", this.$t("message.prompt"), {
                                type: "warning"
                            });
                        }else{
                            downloadfile(res.data.path);
                        }
                    } else {
                        this.delayRequestForReport(key);
                    }
                });
            }, 3000);
        }
    }
};
</script>

<style lang="scss">
.graduate-arrangement {
    .el-form-item__label {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .el-form-item {
        // overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .graduateArrange-table {
        .el-checkbox__inner {
            margin: 0;
        }
        .name-wrapper {
            display: inline-block;
        }
        .demo-table-expand {
            font-size: 0;
            label {
                width: 110px;
                color: #99a9bf;
            }
            .el-form-item {
                margin-right: 0;
                margin-bottom: 0;
                width: 25%;
            }
            .middle-item {
                width: 50%;
            }
            .wide-item {
                width: 100%;
            }
        }
        .cell {
            white-space: pre-line;
            padding: 0 2px;
            text-align: center;
        }
    }
    .save-line {
        text-align: center;
        height: 45px;
        line-height: 32px;
        padding: 5px 5px 15px;
    }
    .line {
        text-align: center;
    }
    .split {
        margin-top: 0;
        border: 1px solid #dcdfe6;
    }
    td .el-form-item__label {
        padding-right: 5px !important;
    }
}
</style>
